import { createUniver, defaultTheme, LocaleType, Tools, FUniver } from '@univerjs/presets';
import type { IWorkbookData, Univer } from '@univerjs/presets'
import { UniverSheetsCorePreset } from '@univerjs/presets/preset-sheets-core';
import { UniverSheetsDataValidationPreset } from '@univerjs/presets/preset-sheets-data-validation'
import { UniverSheetsConditionalFormattingPreset } from '@univerjs/presets/preset-sheets-conditional-formatting'
//@ts-ignore
import UniverPresetSheetsCoreZhCN from '@univerjs/presets/preset-sheets-core/locales/zh-CN';
//@ts-ignore
import UniverPresetSheetsDataValidationZhCN from '@univerjs/presets/preset-sheets-data-validation/locales/zh-CN'
//@ts-ignore
import UniverPresetSheetsConditionalFormattingZhCN from '@univerjs/presets/preset-sheets-conditional-formatting/locales/zh-CN'
//@ts-ignore
import _ from 'lodash'

import '@univerjs/presets/lib/styles/preset-sheets-core.css'
import '@univerjs/presets/lib/styles/preset-sheets-data-validation.css'
import '@univerjs/presets/lib/styles/preset-sheets-conditional-formatting.css'

export class SeUseExcel {
  el: string | HTMLElement;
  defaultJson: Partial<IWorkbookData>;
  config: Object;
  univerAPI: FUniver | undefined;
  univer: Univer | undefined;
  constructor(el: string | HTMLElement, json: Partial<IWorkbookData>, config = {}) {
    this.el = el;
    this.defaultJson = json
    this.config = config
    this.initExcel()
  };
  private initExcel() {
    const { univer, univerAPI } = createUniver({
      locale: LocaleType.ZH_CN,
      locales: {
        zhCN: Tools.deepMerge(
          {},
          UniverPresetSheetsCoreZhCN,
          UniverPresetSheetsDataValidationZhCN,
          UniverPresetSheetsConditionalFormattingZhCN
        )
      },
      theme: defaultTheme,
      presets: [
        UniverSheetsCorePreset(Object.assign({
          container: this.el,
          header: false,
          contextMenu: false
        }, this.config)),
        UniverSheetsDataValidationPreset(),
        UniverSheetsConditionalFormattingPreset()
      ]
    })
    this.univerAPI = univerAPI
    this.univer = univer
    this.univerAPI.createUniverSheet(_.cloneDeep(this.defaultJson))
  }
  dispose() {
    const activeWork = this.univerAPI?.getActiveWorkbook()
    const unitId = activeWork && activeWork.getId()
    unitId && this.univerAPI?.disposeUnit(unitId)
  }
  reload() {
    if (this.univerAPI) {
      this.univerAPI.createUniverSheet(_.cloneDeep(this.defaultJson))
    }
  }
}